package fi.foyt.cs.persistence.dao.system;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import fi.foyt.cs.persistence.dao.GenericDAO;
import fi.foyt.cs.persistence.domainmodel.system.Property;

public class PropertyDAO extends GenericDAO<Property> {
  
  public Property create(String name, String value) {
    EntityManager entityManager = getEntityManager();
    
    entityManager.getTransaction().begin();
    try {
      Property property = new Property();
      property.setName(name);
      property.setValue(value);
      entityManager.persist(property);
      entityManager.getTransaction().commit();
      
      return property;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }
  
  public Property findByName(String name) {
    EntityManager entityManager = getEntityManager();
    Query query = entityManager.createQuery("select p from Property p where p.name = :name");
    query.setParameter("name", name);
    return getSingleResult(query);
  }
  
  public Property updateName(Property property, String name) {
    EntityManager entityManager = getEntityManager();
    
    entityManager.getTransaction().begin();
    try {
      property.setName(name);
      entityManager.persist(property);
      entityManager.getTransaction().commit();
      
      return property;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }
  
  public Property updateValue(Property property, String value) {
    EntityManager entityManager = getEntityManager();
    
    entityManager.getTransaction().begin();
    try {
      property.setValue(value);
      entityManager.persist(property);
      entityManager.getTransaction().commit();
      
      return property;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }
}